package cn.jly.boot.mp.config;

import cn.jly.boot.mp.bean.XMemcachedProperties;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.utils.AddrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @PackageName cn.jly.boot.mp.config
 * @ClassName XMemcachedConfig
 * @Description memcached客户端配置
 * @Author 姬岚洋
 * @Date 2021/1/4 下午 7:14
 */
@Configuration
public class XMemcachedConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(XMemcachedConfig.class);

    @Autowired
    private XMemcachedProperties xMemcachedProperties;

    /**
     * 因为 XMemcachedClient 的创建有比较多的可选项，所以提供了一个 XMemcachedClientBuilder 类用于构建 MemcachedClient。
     * MemcachedClient 是主要接口，操作 Memcached 的主要方法都在这个接口，XMemcachedClient 是它的一个实现。
     *
     * @return
     */
    @Bean
    public MemcachedClient memcachedClient() {
        MemcachedClient memcachedClient = null;

        try {
            final XMemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(xMemcachedProperties.getServers()));
            builder.setConnectionPoolSize(xMemcachedProperties.getPoolSize());
            builder.setOpTimeout(xMemcachedProperties.getOpTimeout());
            memcachedClient = builder.build();
        } catch (Exception e) {
            LOGGER.error("init memcachedClient failed: ", e);
        }

        return memcachedClient;
    }
}
